package com.roy.netty.heatbeat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/8
 * @description:
 **/

public class HeartbeatClinetHandler extends ChannelInboundHandlerAdapter {
    private final ByteBuf HEARTBEAT_BUF = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("heartbeat", Charset.forName("utf-8")));

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //不做任何处理就会触发心跳超时事件。

        //定时写一点东西就不会触发心跳超时
        ctx.executor().scheduleAtFixedRate(()->{
            System.out.println("发送心跳请求");
            ctx.writeAndFlush(HEARTBEAT_BUF);
        },1,3, TimeUnit.SECONDS);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常："+cause.getMessage());
    }
}
